/**
 * @FileName: CommunicationfeeController.java
 * @Author
 * @Description:
 * @Date 2016年9月19日 下午2:31:22
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.controller.admin;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import cn.hpclub.server.model.LocalizedConfig;
import cn.hpclub.server.model.Organization;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.aop.Before;
import com.jfinal.ext.render.excel.PoiRender;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

import cn.hpclub.server.constant.ClientApiConstant;
import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.model.Tariff;
import cn.hpclub.server.model.TariffClass;
import cn.hpclub.server.service.TariffClassRelationService;
import cn.hpclub.server.service.TariffService;
import cn.hpclub.server.util.DateKit;
import cn.hpclub.server.util.InterfaceUtil;

public class TariffController extends BaseAdminController<Tariff>{
    private static Logger log = LoggerFactory.getLogger(RoleController.class);

    /**
     * @Title: 获取角色列表
     */
    public void list(){
        log.debug("RoleController.list");
        List<Entry<String, String>> cityList = TariffService.service.getCityLevelOrgList();
        List<Entry<String, String>> tariffClassList = TariffService.service.getTariffClassList();
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        findByPageByRoleLevel(searchInfo);

        setAttrs(searchInfo);
        setAttr("cityList", cityList);
        setAttr("tariffClassList", tariffClassList);
        initQueryParams();
        render("/admin/tariff_list.tpl");
    }

    /**
     * 导出
     */
    public void export(){
        int cityCode = getCityCode(InterfaceUtil.getOrgId());
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        String sqlOrgFilter = InterfaceUtil.getChlidOrgIdSql(cityCode, Constant.MAX_ORG_LEVEL, true);

        List<Record> list = TariffService.service.export(searchInfo, sqlOrgFilter);

        PoiRender excel = PoiRender.me(list);
        String[] headesExport = TariffService.headesExport;
        String[] columnsExport = TariffService.columnsExport;

        render(excel.sheetName("业务小类配置").headers(headesExport).columns(columnsExport).fileName(generateFileName()));

    }

    private String generateFileName(){
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        String curTime = sdf.format(date);
        String fileName = "业务小类配置-" + curTime + ".xlsx";
        // System.out.println("excel file name:" + fileName);
        try{
            return new String(fileName.getBytes("gbk"), "iso8859-1");
        }
        catch(UnsupportedEncodingException e){
            e.printStackTrace();
        }
        return fileName;
    }

    /**
     * @Title: initQueryParams
     * @Description:TODO void
     */

    private void initQueryParams(){
        initQueryParam("tariff_type", -1);
        initQueryParam("selected_city", -1);
        initQueryParam("tariff_class", -1);
        initQueryParam("is_enabled", -1);
    }

    /**
     * @Title: initQueryParam
     * @Description:TODO
     * @param key
     * @param defualt
     *            void
     */
    private void initQueryParam(String key, int defualt){
        String value = getAttr(key);
        log.info(key + "=" + value);
        if(StrKit.isBlank(value)){
            setAttr(key, defualt);
        }
    }

    /**
     * @Title:findByPageByRoleLevel
     * @Description:根据当前管理员所属角色的等级，获取角色列表 void
     */
    private void findByPageByRoleLevel(ConcurrentHashMap<String, String> searchInfo){
        int cityCode = getCityCode(InterfaceUtil.getOrgId());
        log.info("cityCode=" + cityCode);
        String sqlOrgFilter = InterfaceUtil.getChlidOrgIdSql(cityCode, Constant.MAX_ORG_LEVEL, true);

        String select = TariffService.service.getSqlSelect();
        String sqlExceptSelect = TariffService.service.getSqlFilter(searchInfo, sqlOrgFilter);
        Page<Tariff> pager = Tariff.dao.paginate(getParaToInt(PAGE_NUMBER, 1), getParaToInt(PAGE_SIZE, 10), select,
                                                 sqlExceptSelect);
        setAttr(PAGER, pager);
    }

    private int getCityCode(int orgId){
        if(orgId == InterfaceUtil.ID_TOP){
            return orgId;
        } else{
            Record record = Db.findFirst("SELECT CityCode FROM organization WHERE id=?", orgId);
            return record.getInt("CityCode");
        }
    }

    public void enable(){
        enableTariff(1, "启用");
    }

    public void disable(){
        enableTariff(0, "禁用");
    }

    private void enableTariff(int enabled, String actionName){
        log.info("enabled=" + enabled);
        String[] ids = getParaValues("ids");

        StringBuffer sb = new StringBuffer();
        sb.append("UPDATE tariff SET enabled = " + enabled + ",last_updated_time='"
                + DateKit.toStr(new Date(), "yyyy-MM-dd HH:mm:ss") + "' WHERE id IN (");
        if(ids.length > 0){
            for(int i = 0; i < ids.length; i++){
                if(i == ids.length - 1){
                    sb.append("?");
                } else{
                    sb.append("?,");
                }
            }
            sb.append(")");
        } else{
            ajaxJsonErrorMessage(actionName + "失败");
            return;
        }
        boolean success = Db.update(sb.toString(), (Object[])ids) > 0;
        if(success){
            ajaxJsonSuccessMessage(actionName + "成功");
        } else{
            ajaxJsonErrorMessage(actionName + "失败");
        }
    }

    public void delete(){
        softlyDeleteById("tariff");
        deleteTariffRelation();

        Integer[] ids = getParaValuesToInt("ids");
        //删除属地化配置表相关数据
        for (int i = 0; i < ids.length; i++) {
            LocalizedConfig.dao.deleteLocalizedConfig(LocalizedConfig.BUSINESS_TARIFF,ids[i]);
        }
        //删除业务授权的配置
        LocalizedConfig.dao.deleteAuthConfig(Constant.Table.TABLE_BUSINESS_AUTH_CONFIG,LocalizedConfig.BUSINESS_TARIFF,ids);
        //删除泛店员的配置
        LocalizedConfig.dao.deleteAuthConfig(Constant.Table.TABLE_SPREAD_MEMBER_AUTH_CONFIG,LocalizedConfig.BUSINESS_TARIFF,ids);
        // 熊诗言：删除的同时更新business表
        // 由于唯一性问题先屏蔽掉：deleteBusiness();
    }

    /**
     * 根据code删除，软删
     */
    private void deleteBusiness(){
        String[] ids = getParaValues("ids");
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < ids.length; i++){
            sb.append(ids[i]);
            if(i != ids.length - 1){
                sb.append(",");
            }
        }
        Db.update("UPDATE business set is_deleted=1 WHERE businessCode IN(SELECT tariff.code FROM tariff WHERE tariff.id IN("
                + sb.toString() + "))");
    }

    private void deleteTariffRelation(){
        String[] ids = getParaValues("ids");
        if(ids.length == 0){
            return;
        }
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < ids.length; i++){
            sb.append(ids[i]);
            if(i != ids.length - 1){
                sb.append(",");
            }
        }
        String sql = "DELETE FROM tariff_class_relation WHERE tariff_id IN (" + sb.toString() + ")";
        Db.update(sql);
    }

    /**
     *
     * @Title: add
     * @Description:新增一条首页弹窗数据页面初始化 InterfaceUtil.getParentOrgIdSql(orgId,
     *                              Constant.MAX_ORG_LEVEL);
     */
    public void add(){
        int defaultOrgId = initOrgTree();
        String tariff_class_sql = "SELECT * FROM tariff_class where is_deleted=0 ";
        tariff_class_sql += " and org_id in(" + InterfaceUtil.getParentOrgIdSql(defaultOrgId, Constant.MAX_ORG_LEVEL)
                + ") ";
        List<TariffClass> list = TariffClass.dao.find(tariff_class_sql);
        for(TariffClass tariffClass : list){
            String name = tariffClass.getStr("name");
            if(name.length() > 50){
                tariffClass.set("name", name.substring(0, 47) + "...");
            }
        }
        List<Record> selected = new ArrayList<>();
        setAttr("tariffClassList", list);
        setAttr("tariffClassRelationList", selected);

        List<Organization> cities = Organization.dao.getOrganizationCityList(InterfaceUtil.getOrgId());
        setAttr("cities", cities);
        render("/admin/communication_fee_input.tpl");
    }

    /**
     *
     * @Title: edit
     * @Description:修改一条资费管理数据页面初始化
     */
    public void edit(){
        String id = getPara("id", null);
        List<Record> selected = new ArrayList<>();
        Integer businessId = null;
        if(StrKit.notBlank(id)){
            Tariff communicationFee = Tariff.dao.findById(id);
            String description = communicationFee.getStr(Tariff.DESCRIPTION);
            // 将换行标签替换为回车换行符
            if(StrKit.notBlank(description) && description.contains("<br/>")){
                description = description.replace("<br/>", "\r\n");
            }
            communicationFee.set("description", description);
            setAttr("communicationFee", communicationFee);
            selected = Db.find(
                               "SELECT tr.id,tc.name,tc.enabled,tr.tariff_id,tr.tariff_class_id from tariff_class_relation tr"
                                       + " LEFT JOIN tariff_class tc ON tr.tariff_class_id = tc.id WHERE tr.tariff_id =? AND tc.is_deleted = 0",
                               id);

            // 熊诗言：修改的时候找到business的id同时修改它
            // 由于唯一性问题先屏蔽掉：businessId = Business.dao.findFirst("SELECT id from
            // business where businessCode=?",
            // communicationFee.getStr(Tariff.CODE)).getInt(Business.ID);
            // setAttr("businessId", businessId);
        }

        int defaultOrgId = initOrgTree();
        String tariff_class_sql = "SELECT * FROM tariff_class where is_deleted=0 ";
        tariff_class_sql += " and org_id in(" + InterfaceUtil.getParentOrgIdSql(defaultOrgId, Constant.MAX_ORG_LEVEL)
                + ") ";
        List<TariffClass> list = TariffClass.dao.find(tariff_class_sql);
        for(Record record : selected){
            String name = record.getStr("name");
            if(name.length() > 50){
                record.set("name", name.substring(0, 47) + "...");
            }
            int tariff_class_id = record.getInt("tariff_class_id");
            for(TariffClass tariffClass : list){
                int p_id = tariffClass.getInt("id");
                if(p_id == tariff_class_id){
                    list.remove(tariffClass);
                    break;
                }
            }
        }
        for(TariffClass tariffClass : list){
            String tariffClassName = tariffClass.getStr("name");
            if(tariffClassName.length() > 50){
                tariffClass.set("name", tariffClassName.substring(0, 47) + "...");
            }
        }
        setAttr("tariffClassList", list);
        setAttr("tariffClassRelationList", selected);

        List<Organization> cities = Organization.dao.getOrganizationCityList(InterfaceUtil.getOrgId());
        setAttr("cities", cities);
        List<LocalizedConfig> configs = LocalizedConfig.dao.findByBusinessAndId(LocalizedConfig.BUSINESS_TARIFF,id);
        setAttr("localizedConfig", configs);

        render("/admin/communication_fee_input.tpl");
    }

    /**
     *
     * @Title: save
     * @Description:保存一条首页弹窗数据
     */
    @Before(Tx.class)
    public void save(){
        String code = getPara("code", null);
        int org_id = InterfaceUtil.getOrgId();
        int city_org_id = getCityCode(org_id);
        Tariff obj = new Tariff();
        Record record = null;

        List<Record> list = TariffService.service.getTariffByCityAndCodeForDeleted(city_org_id, code);
        if(list != null && list.size() > 0){
            record = list.get(0);
        }
        String tariffClassIds = getPara("tariff_class_ids", null);


        int tariffId = getParaToInt("communicationId", 0);
        boolean isEdit = false;//判断是新增还是编辑
        int localized_exist = LocalizedConfig.LOCALIZED_UNIFIED;
        if(tariffId != 0){// 更新时删除原有的资费大类关系数据，后续重新保存
            isEdit = true;
            localized_exist = Tariff.dao.findById(tariffId).getInt(Tariff.LOCALIZED);//去获取原来的属地化信息
            TariffClassRelationService.service.deleteRelationByTariffId(tariffId);
        }
        String comm_type = getPara("comm_type", null);
        String name = getPara("name", null);
        String detail = getPara("detail", null);
        String start_time = getPara("start_time", null);
        String end_time = getPara("end_time", null);
        String sort = getPara("sort", null);
        String creator = getPara("creator", null);
        int is_activity = getParaToInt("is_activity", 0);// 是否活动业务
        String activity_name = getPara("activity_name", null);// 活动名称
        String description = getPara("description", null);// 资费详情
        int localized = getParaToInt("localized", 0);//默认为非属地化
        if(StrKit.isBlank(creator)){
            creator = InterfaceUtil.getAdminId() + "";
        }
        // 获取系统当前时间
        String create_time = DateKit.toStr(new Date(), "yyyy-MM-dd HH:mm:ss");
        // 检查必填字段
        if(StrKit.isBlank(tariffClassIds) || StrKit.isBlank(comm_type) || StrKit.isBlank(name) || StrKit.isBlank(code)
                || StrKit.isBlank(detail) || StrKit.isBlank(start_time) || StrKit.isBlank(end_time)
                || StrKit.isBlank(sort) || StrKit.isBlank(creator)){
            throw new IllegalArgumentException("参数错误");
        }
        // 空格转换为换行
        if(StrKit.notBlank(description)){
            description = description.replace(" ", "<br/>");
        }

        obj.set(Tariff.TYPE, comm_type);
        obj.set(Tariff.NAME, name);
        obj.set(Tariff.CODE, code);
        obj.set(Tariff.DETAIL, detail);
        obj.set(Tariff.START_DATE, start_time);
        obj.set(Tariff.END_DATE, end_time);
        obj.set(Tariff.SORT, sort);
        obj.set(Tariff.LAST_UPDATED_TIME, new Date());
        obj.set(Tariff.LAST_UPDATED_BY, creator);
        obj.set(Tariff.IS_ACTIVITY, is_activity);// 是否活动业务
        obj.set(Tariff.ACTIVITY_NAME, activity_name);// 活动名称
        obj.set(Tariff.DESCRIPTION, description);// 资费详情
        obj.set(Tariff.LOCALIZED, localized);// 属地化信息

        if(tariffId != 0){
            // 更新商品信息
            obj.set(Tariff.ID, tariffId);
            obj.update();

            // 熊诗言:更新的时候同时更新business
            /*
             * 由于唯一性问题先屏蔽掉：Db.update("update " + Constant.Table.BUSIENSS +
             * " set " + Business.BUSINESS_CODE + "=?," + Business.BUSINESS_NAME
             * + "=? where " + Business.ID + "=?", new Object[] {
             * code,name,getPara("businessId")});
             */
        } else{
            if(record != null){
                obj.set(Tariff.ID, record.getInt(Tariff.ID));
                obj.set(Tariff.IS_DELETED, 0);
                if(obj.update()){
                    tariffId = obj.getInt(Tariff.ID);
                }
            } else{
                obj.set(Tariff.CREATE_BY, creator);// 新增时才更新创建人Id
                obj.set(Tariff.ORG_ID, city_org_id);
                obj.set(Tariff.CREATE_TIME, create_time);
                if(obj.save()){
                    tariffId = obj.getInt(Tariff.ID);
                }
            }


            // 熊诗言:新增的时候同时新增business
            /*
             * 由于唯一性问题先屏蔽掉：Db.update("insert into " + Constant.Table.BUSIENSS +
             * "(" + Business.BUSINESS_CODE + "," + Business.BUSINESS_NAME +
             * ") value(?,?)", new Object[] {code , name});
             */
        }
        List<Integer> tariffClassIdList = str2Ints(tariffClassIds);
        TariffClassRelationService.service.saveRelation(tariffId, tariffClassIdList);

        Integer[] city_ids = getParaValuesToInt("city_ids");
        LocalizedConfig.dao.localizedConfig(LocalizedConfig.BUSINESS_TARIFF, tariffId, localized, city_ids);
        if(isEdit){
            LocalizedConfig.dao.deleteAuthConfig(LocalizedConfig.BUSINESS_TARIFF,tariffId,localized_exist,localized,city_ids);
        }

        redirect("/tariff/list");
    }

    private List<Integer> str2Ints(String strIds) {
        List<Integer> intList = new ArrayList<>();
        if(StrKit.isBlank(strIds)){return  intList;}
        if(strIds.contains(",")){
            String[] tariffClassIdArr = strIds.split(",");
            for(String tariffClassId : tariffClassIdArr){
                intList.add(Integer.parseInt(tariffClassId));
            }
        } else{
            intList.add(Integer.parseInt(strIds));
        }
        return intList;
    }

    public void validityCodeUnique(){
        JSONObject jo = null;
        String code = getPara("code", "");
        int tariffId = getParaToInt("communicationId", 0);
        int org_id = InterfaceUtil.getOrgId();
        int city_org_id = getCityCode(org_id);
        boolean flag = TariffService.service.getTariffByCityAndCode(city_org_id, code, tariffId);
        if(!flag){
            jo = setResponseObj(ClientApiConstant.ResultCode.SUCCESS_CODE, "资费代码唯一可用", null);
        } else{
            jo = setResponseObj(ClientApiConstant.ResultCode.FAILED, "资费代码在当前地市已存在", null);
        }
        renderJson(jo.toString());
    }
}
